// import Vue from 'vue'
/************************经纬度相关  begin*******************************/
const PI = 3.14159265358979324;
const x_pi = 3.14159265358979324 * 3000.0 / 180.0;
const delta = function(lat, lon) {
  // Krasovsky 1940
  //
  // a = 6378245.0, 1/f = 298.3
  // b = a * (1 - f)
  // ee = (a^2 - b^2) / a^2;
  var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
  var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
  var dLat = transformLat(lon - 105.0, lat - 35.0);
  var dLon = transformLon(lon - 105.0, lat - 35.0);
  var radLat = lat / 180.0 * PI;
  var magic = Math.sin(radLat);
  magic = 1 - ee * magic * magic;
  var sqrtMagic = Math.sqrt(magic);
  dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
  dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
  return {
    'lat': dLat,
    'lon': dLon
  };
}

const transformLat = function(x, y) {
  var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
  ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
  ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
  return ret;
}
const transformLon = function(x, y) {
  var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
  ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
  ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
  return ret;
}

//WGS-84 to GCJ-02
const gcj_encrypt = function(wgsLat, wgsLon) {
  if (outOfChina(wgsLat, wgsLon))
    return {
      'lat': wgsLat,
      'lon': wgsLon
    };

  var d = delta(wgsLat, wgsLon);
  return {
    'lat': wgsLat + d.lat,
    'lon': wgsLon + d.lon
  };
}

/**
 * GCJ02 转换为 WGS84
 */
const gcj02towgs84 = function(lng, lat) {
  if (outOfChina(lng, lat)) {
    return [lng, lat]
  } else {
    var dlat = transformlat(lng - 105.0, lat - 35.0);
    var dlng = transformLon(lng - 105.0, lat - 35.0);
    var radlat = lat / 180.0 * PI;
    var magic = Math.sin(radlat);
    magic = 1 - ee * magic * magic;
    var sqrtmagic = Math.sqrt(magic);
    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
    dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
    mglat = lat + dlat;
    mglng = lng + dlng;
    return [lng * 2 - mglng, lat * 2 - mglat]
  }
}

const outOfChina = function(lat, lon) {
  if (lon < 72.004 || lon > 137.8347)
    return true;
  if (lat < 0.8293 || lat > 55.8271)
    return true;
  return false;
}


/************************经纬度相关  end*******************************/


const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 个位数补齐十位数
function setTimeDateFmt(s) {
  return s < 10 ? '0' + s : s;
}

// 判断用户是否授权某项权限
function checkUserAuth(authName = 'scope.writePhotosAlbum', modalTitle = '是否重新授权系统相册的存储功能') {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success(res) {
        // 判断是否拥有此权限进行拉起授权  和 重新授权功能
        if (!res.authSetting[authName]) {
          // 未授权此项权限 拉起授界面
          uni.authorize({
            scope: authName,
            success() {
              // 授权成功后 就可以执行 需要权限的  操作函数了
              //在这里调用uni.saveImageToPhotosAlbum(OBJECT)
              // 使用已授权的功能
              resolve()
            },
            fail(err) {
              /*
               第一次拒绝授权后必须在 uni.authorize的fail中使用
               uni.openSetting 才能进入设置界面打开授权按钮
               */
              // 这里必须经过一个confirm 不然也会出现问题（啥问题我也不知道）
              uni.showModal({
                title: modalTitle,
                success(res) {
                  if (res.confirm) {
                    uni.openSetting({
                      success(res) {
                        console.log(res)
                        if (res.authSetting[
                            authName]) { // 勾选了权限
                          resolve()
                          console.log('开启权限成功');
                        } else {
                          console.log('开启权限失败');
                          reject()
                        }
                      },
                      fail() {
                        console.log('开启权限失败');
                        reject()
                      }
                    });
                  } else if (res.cancel) {
                    console.log('拒绝开启开启权限');
                    reject()
                  }
                }
              });
            }
          });
        } else {
          //在这里调用uni.saveImageToPhotosAlbum(OBJECT)
          // 使用已授权的功能
          resolve()
        }
      }
    });
  })
}

//百度OCR access_token 有效期为 2592000 秒 / 30天
function getBaiduOcrToken() {
  // console.log('百度OCR keys:', Vue.prototype.baiduKeys)
  return new Promise((resolve, reject) => {
    uni.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token',
      method: 'POST',
      data: {
        grant_type: 'client_credentials',
        client_id: Vue.prototype.baiduKeys.client_id, //API Key
        client_secret: Vue.prototype.baiduKeys.client_secret //Secret Key
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        console.log('百度token：', res.data);
        if (res.data.access_token) {
          resolve(res.data.access_token)
        } else {
          reject()
        }
      },
      fail(err) {
        reject(err)
      }
    });
  })
}



// 生成唯一流水号 UUID
function getFlowId() {
  const now = new Date()
  let month = now.getMonth() + 1
  let day = now.getDate()
  let hour = now.getHours()
  let minutes = now.getMinutes()
  let seconds = now.getSeconds()
  month = setTimeDateFmt(month)
  day = setTimeDateFmt(day)
  hour = setTimeDateFmt(hour)
  minutes = setTimeDateFmt(minutes)
  seconds = setTimeDateFmt(seconds)
  let flowId = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math
    .random() * 1000000)).toString();
  return flowId;
}

//阿拉伯数字 1 转中文数字 一
const toChineseNumber = (n) => {
  if (!Number.isInteger(n) && n < 0) {
    throw Error('请输入自然数');
  }
  const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const positions = ['', '十', '百', '千', '万', '十万', '百万', '千万', '亿', '十亿', '百亿', '千亿'];
  const charArray = String(n).split('');
  let result = '';
  let prevIsZero = false;
  //处理0  deal zero
  for (let i = 0; i < charArray.length; i++) {
    const ch = charArray[i];
    if (ch !== '0' && !prevIsZero) {
      result += digits[parseInt(ch)] + positions[charArray.length - i - 1];
    } else if (ch === '0') {
      prevIsZero = true;
    } else if (ch !== '0' && prevIsZero) {
      result += '零' + digits[parseInt(ch)] + positions[charArray.length - i - 1];
    }
  }
  //处理十 deal ten
  if (n < 100) {
    result = result.replace('一十', '十');
  }
  return result;
}

module.exports = {
  vuemixin: {
    created: function() {
      console.log(1)
    }
  },
  checkUserAuth: checkUserAuth,
  formatTime: formatTime,
  getFlowId: getFlowId,
  gcj_encrypt: gcj_encrypt,
  gcj02towgs84: gcj02towgs84,
  getBaiduOcrToken: getBaiduOcrToken,
  toChineseNumber
}
